const db = require("@/db/index");
const bcrypt = require("bcryptjs");

// 获取当前角色信息
exports.getInfo = (req, resp) => {
  const id = req.auth.id;
  let sql = "";

  if (req.auth.role) {
    sql = `select * from users where id = ?`;
  } else {
    sql = `select * from employee where id = ?`;
  }
  // if (!req.auth.role) sql = `select * from employee where id = ?`;

  db.query(sql, id, (err, res) => {
    if (err) return resp.err(err);
    if (res.length !== 1) return resp.err("获取用户信息失败！");
    resp.ok({ ...res[0], password: "" });
  });
};

// 修改密码
exports.updatePWD = (req, resp) => {
  const pwdInfo = req.body;
  const id = req.auth.id;
  let querySql;
  let updateSql;
  if (pwdInfo.role == 1) {
    querySql = `select * from users where id = ?`;
    updateSql = `update users set password = ? where id = ?`;
  }
  if (pwdInfo.role == 2) {
    querySql = `select * from employee where id = ?`;
    updateSql = `update employee set password = ? where id = ?`;
  }
  pwdInfo.newpassword = bcrypt.hashSync(pwdInfo.newpassword, 10);

  db.query(querySql, id, (err, res) => {
    if (err) return resp.err(err);

    const pwd = bcrypt.compareSync(pwdInfo.oldpassword, res[0].password);
    if (!pwd) return resp.err("原密码错误！");

    db.query(updateSql, [pwdInfo.newpassword, id], (err, res) => {
      if (err) return resp.err(err);
      if (res.affectedRows !== 1) return resp.err("修改密码失败！");
      resp.ok("修改密码成功！");
    });
  });
};

// 修改用户信息
exports.update = (req, resp) => {
  const userInfo = req.body;
  const id = req.auth.id;
  let sql;
  if (userInfo.role == 1) sql = `update users set ? where id = ?`;
  if (userInfo.role == 2) sql = `update employee set ? where id = ?`;
  delete userInfo.role;
  if (userInfo.password)
    userInfo.password = bcrypt.hashSync(userInfo.password, 10);
  db.query(sql, [userInfo, id], (err, res) => {
    if (err) return resp.err(err);
    if (res.affectedRows !== 1) return resp.err("用户信息修改失败！");
    resp.ok("用户信息修改成功！");
  });
};
